/*
 *  scoreBoard - RemoteIO.cpp
 *  Copyright 2011 W. Reckman. All rights reserved.
 */
#include "RemoteIO.h"

const int RemoteIO::DEFAULT_FILE_XFER_PORT = 8775;
const int RemoteIO::DIR_SCAN_INTERVAL = 1000;

RemoteIO::RemoteIO()
: s( Settings::getInstance() ), photoboothPath( 0 ),
  nextDirScan( ofGetElapsedTimeMillis() + DIR_SCAN_INTERVAL ),
  fileXferServer( new ofxFileTransferServer( DEFAULT_FILE_XFER_PORT ) )
{}

void RemoteIO::setup( bool reportExistingFiles_ ) {
	reportExistingFiles = reportExistingFiles_;
	photoboothPath = s.getValue( "photobooth_path", "player-images" );
	
	fileXferServer->startThread();
	
	if ( ! reportExistingFiles ) {
		vec_string* files = getNewPhotoboothFiles();
		knownPhotoboothFiles.insert( knownPhotoboothFiles.end(), files->begin(), files->end() );
		delete files;
	}
}

void RemoteIO::update() {
	if ( ofGetElapsedTimeMillis() > nextDirScan ) {
		nextDirScan = ofGetElapsedTimeMillis() + DIR_SCAN_INTERVAL;
		
		vec_string* files = getNewPhotoboothFiles();
		
		for ( int i = 0; i < files->size(); ++i ) {
			reportDelayFiles.push_back( FileDelayInfo( ofGetElapsedTimef() + REPORT_DELAY, (*files)[i] ) );
			
			//OLD
			//argsPhotoboothFile.filePath = (*files)[i];
			//ofNotifyEvent( onNewPhotoboothFile, argsPhotoboothFile, this );
		}
		
		knownPhotoboothFiles.insert( knownPhotoboothFiles.end(), files->begin(), files->end() );
		delete files;
	}
	
	handleReportDelayFiles();
}


/*********************
 * PRIVATE FUNCTIONS *
 *********************/

const float RemoteIO::REPORT_DELAY = 2.0f;

RemoteIO::vec_string* RemoteIO::getNewPhotoboothFiles() {
	vec_string* result = new vec_string();
	
	if ( photoboothPath == 0 ) {
		ofLog( OF_LOG_WARNING, "(RemoteIO.cpp) No photobooth path set, cannot scan for new files" );
		return 0;
	}
	
	int numFiles = dirLister.listDir( *photoboothPath );
	for ( int i = 0; i < numFiles; ++i ) {
		string path = dirLister.getPath( i );
		bool found = false;
		
		for ( int j = 0; j < knownPhotoboothFiles.size(); ++j ) {
			if ( knownPhotoboothFiles[j] == path ) {
				found = true;
				break;
			}
		}
		
		if ( ! found ) result->push_back( path );
	}
	
	return result;
}

void RemoteIO::handleReportDelayFiles() {
	float now = ofGetElapsedTimef();
	
	for ( int i = 0; i < reportDelayFiles.size(); ++i ) {
		FileDelayInfo& fdi = reportDelayFiles[i];
		if ( fdi.timeToReport <= now ) {
			argsPhotoboothFile.filePath = fdi.filePath;
			ofNotifyEvent( onNewPhotoboothFile, argsPhotoboothFile, this );
			
			reportDelayFiles.erase( reportDelayFiles.begin() + i );
			--i;
		}
	}
}
